<template>
  <div class="product-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">商品管理</h1>
        <p class="page-subtitle">
          管理系统商品信息，支持SPU和SKU的增删改查操作
        </p>
      </div>
      <el-button type="primary" @click="goToAddPage" class="add-btn">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
        新增商品
      </el-button>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.spuName"
          placeholder="搜索商品名称"
          class="search-input"
          clearable
        >
          <template #prefix>
            <svg class="search-icon" viewBox="0 0 24 24" fill="currentColor">
              <path
                d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
              />
            </svg>
          </template>
        </el-input>
        <el-select
          v-model="searchForm.categoryId"
          placeholder="选择分类"
          clearable
          class="search-select"
        >
          <el-option
            v-for="category in categoryOptions"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        <el-select
          v-model="searchForm.status"
          placeholder="选择状态"
          clearable
          class="search-select"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="2" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="productList"
        style="width: 100%"
        class="product-table"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="spuName" label="商品名称" min-width="120" />
        <el-table-column prop="subTitle" label="商品标语" min-width="150" />
        <el-table-column prop="categoryName" label="分类" width="80">
          <template #default="scope">
            <el-tag size="small" type="primary">
              {{ scope.row.categoryName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="labelName" label="标签" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.labelName" size="small" type="success">
              {{ scope.row.labelName }}
            </el-tag>
            <span v-else class="no-label">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="skuCount" label="SKU数量" width="100">
          <template #default="scope">
            <el-tag
              size="small"
              type="info"
              class="clickable-sku-count"
              @click="openSkuDialog(scope.row)"
              :title="`点击查看 ${scope.row.spuName} 的SKU列表`"
            >
              <svg
                class="click-icon"
                viewBox="0 0 24 24"
                fill="currentColor"
                width="12"
                height="12"
              >
                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
              </svg>
              {{ scope.row.skuCount || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="主图" width="140">
          <template #default="scope">
            <div class="image-preview">
              <img
                v-if="
                  scope.row.mainImageList && scope.row.mainImageList.length > 0
                "
                :src="scope.row.mainImageList[0]"
                :alt="scope.row.spuName"
                class="product-image"
                @click="previewImage(scope.row.mainImageList[0])"
              />
              <div v-else class="no-image">暂无图片</div>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="modifiedTime" label="修改时间" width="180" />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="goToEditPage(scope.row)"
              class="action-btn"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="previewProduct(scope.row)"
              class="action-btn"
            >
              预览
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
              class="action-btn"
            >
              {{ scope.row.status === 1 ? "下架" : "上架" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- SKU查看对话框 -->
    <el-dialog v-model="skuDialogVisible" title="查看SKU" width="1000px">
      <div class="sku-header">
        <div class="sku-info">
          <h3>{{ currentSpu?.spuName }}</h3>
          <p>分类：{{ currentSpu?.categoryName }}</p>
        </div>
      </div>

      <el-table
        :data="skuList"
        style="width: 100%"
        class="sku-table"
        v-loading="skuLoading"
      >
        <el-table-column prop="specs" label="规格属性" min-width="200">
          <template #default="scope">
            <div class="specs-display">
              <el-tag
                v-for="(value, key) in parseSpecs(scope.row.specs)"
                :key="key"
                size="small"
                class="spec-tag"
              >
                {{ key }}: {{ value }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="销售价" width="100">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="marketPrice" label="市场价" width="100">
          <template #default="scope"> ¥{{ scope.row.marketPrice }} </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="warnStock" label="预警库存" width="100" />
        <el-table-column label="SKU图片" width="120">
          <template #default="scope">
            <div class="image-preview">
              <img
                v-if="scope.row.image"
                :src="scope.row.image"
                :alt="`SKU ${scope.row.skuCode}`"
                class="sku-image"
                @click="previewImage(scope.row.image)"
              />
              <div v-else class="no-image">暂无图片</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { postWithAuth, getWithAuth } from "@/utils/request";
import { useRouter } from "vue-router";

// 类型定义
interface ProductSpu {
  id?: string;
  spuCode: string;
  spuName: string;
  subTitle: string;
  categoryId: string | number;
  categoryName?: string;
  labelId?: string | number;
  labelName?: string;
  mainImageList: string[];
  detailImageList: string[];
  description: string;
  status: number;
  skuCount?: number;
  modifiedTime?: string;
  productSkus?: ProductSku[];
}

interface ProductSku {
  id?: string;
  skuCode: string;
  spuId: string | number;
  specs: string | Record<string, any>;
  price: number;
  marketPrice: number;
  costPrice: number;
  stock: number;
  warnStock: number;
  image: string;
  status: number;
}

interface CategoryDTO {
  id: string;
  name: string;
  level: number;
  children?: CategoryDTO[];
}

interface SearchForm {
  spuName: string;
  categoryId: string | number;
  status: number | null;
}

interface Pagination {
  pageIndex: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const loading = ref(false);
const productList = ref<ProductSpu[]>([]);
const router = useRouter();

// SKU相关
const skuDialogVisible = ref(false);
const skuLoading = ref(false);
const skuList = ref<ProductSku[]>([]);
const currentSpu = ref<ProductSpu | null>(null);

// 分类和标签
const categoryList = ref<CategoryDTO[]>([]);

// 分类选项（支持二级分类）
const categoryOptions = computed(() => {
  const options: CategoryDTO[] = [];
  const addCategories = (categories: CategoryDTO[]) => {
    categories.forEach((category) => {
      if (category.level === 2) {
        options.push(category);
      }
      if (category.children) {
        addCategories(category.children);
      }
    });
  };
  addCategories(categoryList.value);
  return options;
});

// 搜索表单
const searchForm = reactive<SearchForm>({
  spuName: "",
  categoryId: "",
  status: null,
});

// 分页
const pagination = reactive<Pagination>({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true;
  try {
    const response = await postWithAuth("/internal/product/pageList", {
      spuName: searchForm.spuName,
      categoryId: searchForm.categoryId,
      status: searchForm.status,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
    });

    if (response.code === 0) {
      productList.value = response.data.list;
      pagination.total = parseInt(response.data.total);
    } else {
      ElMessage.error(response.message || "获取商品列表失败");
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await postWithAuth("/internal/category/pageListByName", {
      name: "",
      pageIndex: 1,
      pageSize: 1000,
    });

    if (response.code === 0) {
      categoryList.value = response.data.list;
    } else {
      ElMessage.error(response.message || "获取分类列表失败");
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  }
};

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1;
  fetchProductList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.spuName = "";
  searchForm.categoryId = "";
  searchForm.status = null;
  pagination.pageIndex = 1;
  fetchProductList();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageIndex = 1;
  fetchProductList();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchProductList();
};

// 跳转到新增页面
const goToAddPage = () => {
  router.push("/product/add");
};

// 跳转到编辑页面
const goToEditPage = (row: ProductSpu) => {
  router.push(`/product/edit/${row.id}`);
};

// 预览商品
const previewProduct = (row: ProductSpu) => {
  router.push(`/product/detail/${row.id}`);
};

// 切换状态
const toggleStatus = async (row: ProductSpu) => {
  const newStatus = row.status === 1 ? 2 : 1;
  const actionText = newStatus === 1 ? "上架" : "下架";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}商品"${row.spuName}"吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth("/internal/product/upAndDown", {
      id: row.id,
      status: newStatus,
    });

    if (response.code === 0) {
      ElMessage.success(`${actionText}成功`);
      fetchProductList();
    } else {
      ElMessage.error(response.message || `${actionText}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("切换状态失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 打开SKU管理对话框
const openSkuDialog = async (row: ProductSpu) => {
  currentSpu.value = row;
  skuDialogVisible.value = true;
  await fetchSkuList(row.id as string);
};

// 获取SKU列表
const fetchSkuList = async (spuId: string) => {
  skuLoading.value = true;
  try {
    const response = await getWithAuth(
      `/internal/product/skuList?spuId=${spuId}`
    );

    if (response.code === 0) {
      skuList.value = response.data;
    } else {
      ElMessage.error(response.message || "获取SKU列表失败");
    }
  } catch (error) {
    console.error("获取SKU列表失败:", error);
    ElMessage.error("获取SKU列表失败");
  } finally {
    skuLoading.value = false;
  }
};

// 解析规格属性
const parseSpecs = (specs: string | Record<string, any>) => {
  if (typeof specs === "string") {
    try {
      return JSON.parse(specs);
    } catch {
      return {};
    }
  }
  return (specs as Record<string, any>) || {};
};

// 状态标签类型
const getStatusTagType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "info",
    1: "success",
    2: "danger",
  };
  return statusMap[status] || "info";
};

// 状态标签
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "待审核",
    1: "上架",
    2: "下架",
  };
  return statusMap[status] || "未知";
};

// 图片预览
const previewImage = (imageUrl: string) => {
  window.open(imageUrl, "_blank");
};

// SKU规格属性处理函数 - 在商品管理页面中不需要这些函数

// 校验函数 - 在商品管理页面中不需要这些函数

// 页面加载时获取数据
onMounted(() => {
  fetchProductList();
  fetchCategoryList();
});
</script>

<style scoped>
.product-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  /* background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  font-weight: 500;
}

.btn-icon {
  width: 16px;
  height: 16px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.search-select {
  width: 200px;
}

.search-icon {
  width: 16px;
  height: 16px;
  color: #909399;
}

.product-table {
  margin: 0;
  padding-left: 20px;
}

.action-btn {
  margin-right: 8px;
}

.action-btn:last-child {
  margin-right: 0;
}

.clickable-sku-count {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.clickable-sku-count::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.4),
    transparent
  );
  transition: left 0.5s ease;
}

.clickable-sku-count:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  border-color: #409eff;
  background-color: #409eff !important;
  color: white !important;
}

.clickable-sku-count:hover::before {
  left: 100%;
}

.clickable-sku-count:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
}

.click-icon {
  margin-right: 4px;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.clickable-sku-count:hover .click-icon {
  opacity: 1;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.no-label {
  color: #909399;
  font-style: italic;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.product-form {
  padding: 20px 0;
}

.tree-select {
  width: 100%;
}

.select-input {
  width: 100%;
}

/* SKU查看样式 */
.sku-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.sku-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.sku-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.sku-table {
  margin-bottom: 20px;
}

.specs-display {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.spec-tag {
  margin: 2px;
}

/* 图片预览样式 */
.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image,
.sku-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.product-image:hover,
.sku-image:hover {
  transform: scale(1.1);
}

.no-image {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input,
  .search-select {
    width: 100%;
  }

  .sku-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>
